#include "ArduinoCommand.h"
#include <stdlib.h>

using namespace std;

ArduinoCommand::ArduinoCommand(ComController* comController) {
    this->_ComController = comController;
}

Command* ArduinoCommand::CreateCommand(string line) {
    string command;
    int endPos;
    endPos = line.find(" ");

    command = line.substr(0, endPos);

    line = line.substr(endPos, line.length() - endPos);
        
        
    if (!command.compare("#SENDDATA")) {
        int sendCommandCode = this->GetNumber(line, ',');
        
        endPos = line.find(',');
        line = line.substr(endPos + 1, line.length() - endPos - 1);
        
        
        endPos = line.length();
        string sendData = line.substr(0, endPos);

        sendData = this->TrimLine(sendData);

        int sendDataCode = atoi(sendData.c_str());

        return new DirectCommand(sendCommandCode, sendDataCode, this->_ComController);
    }

    if (!command.compare("#ADDMOVE")) {
        endPos = line.find(",");
        string sendCommand = line.substr(0, endPos);
        sendCommand = this->TrimLine(sendCommand);
        int sendCommandCode = atoi(sendCommand.c_str());
        line = line.substr(endPos + 1, line.length() - endPos - 1);

        endPos = line.length();
        string sendData = line.substr(0, endPos);
        sendData = this->TrimLine(sendData);
        int sendDataCode = atoi(sendData.c_str());

        return new DirectCommand(sendCommandCode, sendDataCode, this->_ComController);
    }
    
    if (!command.compare("#WAIT")) {
        string delayString = this->TrimLine(line);
        int delayInt = atoi(delayString.c_str());
        return new DelayCommand(delayInt);
    }
    
    return NULL;
}

int ArduinoCommand::GetNumber(string line, char delimitter)
{
        int endPos = line.find(delimitter);
        string sendCommand = line.substr(0, endPos);
        sendCommand = this->TrimLine(sendCommand);
        int number = atoi(sendCommand.c_str());
        return number;
}

void ArduinoCommand::RunFileScript(string scriptFileName) {
    string line;
    Command* cmd;
    
    ifstream scriptFile(scriptFileName.c_str());
    if (scriptFile.is_open()) {
        while (getline(scriptFile, line)) {
            line = this->TrimLine(line);
                cmd = this->CreateCommand(line);
                if(cmd != NULL)
                {
                        cmd->Execute();
                        //cmd->~Command();                        
                }
        }
        scriptFile.close();
    }
}


string ArduinoCommand::TrimLine(string line) {    

    line = line.erase(line.find_last_not_of(" \n\r\t") + 1);    
    line = line.substr(line.find_first_not_of(" \t"));
    return line;
}